package com.example.demo.generator.codegen.exception;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class SqlParseException extends Exception {
    private final String sql;
    private final int errorPosition;
    private final String suggestion;
    private final String errorCode;

    public SqlParseException(String message) {
        this(message, null, -1, null, "PARSE_ERROR");
    }

    public SqlParseException(String message, Throwable cause) {
        this(message, null, -1, null, "PARSE_ERROR", cause);
    }

    public SqlParseException(String message, String sql, int errorPosition, String suggestion, String errorCode) {
        super(message);
        this.sql = sql;
        this.errorPosition = errorPosition;
        this.suggestion = suggestion;
        this.errorCode = errorCode;
    }

    public SqlParseException(String message, String sql, int errorPosition, String suggestion, String errorCode, Throwable cause) {
        super(message, cause);
        this.sql = sql;
        this.errorPosition = errorPosition;
        this.suggestion = suggestion;
        this.errorCode = errorCode;
    }

    public String getDetailedMessage() {
        StringBuilder sb = new StringBuilder();
        sb.append("SQL 解析失败 [").append(errorCode).append("]: ").append(getMessage());

        if (sql != null) {
            sb.append("\nSQL: ").append(sql);
            if (errorPosition > 0) {
                sb.append("\n错误位置: ").append(errorPosition);
                sb.append("\n位置提示: ");
                // 使用 Hutool 的字符串重复方法
                String pointer = StrUtil.repeat(" ", Math.max(0, errorPosition - 1)) + "^";
                sb.append("\n").append(sql).append("\n").append(pointer);
            }
        }

        if (suggestion != null) {
            sb.append("\n修复建议: ").append(suggestion);
        }

        return sb.toString();
    }
}
